import { login, logout } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import cache from '@/plugins/cache'

const state = {
  userInfo:{
      accessToken: getToken(),
      refreshToken: cache.local.get('refreshToken'),
      userId: cache.local.get('userId'),
      userName: cache.local.get('userName'),
  }
}

const mutations = {
    SET_ACCESS_TOKEN: (state, accessToken) => {
      state.userInfo.accessToken = accessToken
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      state.userInfo.refreshToken = refreshToken
      cache.local.set('refreshToken',refreshToken)
    },
    SET_NAME: (state, userName) => {
      state.userInfo.userName = userName
      cache.local.set('userName',userName)
    },
    SET_ID: (state, userId) => {
      state.userInfo.userId = userId
      cache.local.set('userId',userId)
    },
    
}
const actions = {
    // 登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then((res) => {
            setToken(res.data.data.accessToken)
            commit('SET_ACCESS_TOKEN', res.data.data.accessToken)
            commit('SET_REFRESH_TOKEN', res.data.data.refreshToken)
            commit('SET_NAME', res.data.data.userName)
            commit('SET_ID', res.data.data.userId)
            resolve()
        }).catch((error) => {
            reject(error)
        })
      })
    },

    // 退出系统
    logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.userInfo.userId).then(() => {
          commit('SET_ACCESS_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '')
          commit('SET_NAME', '')
          commit('SET_ID', '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
}

export default
{
    namespaced: true,
    state,
    mutations,
    actions
}
